package virtualReader;

import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;
import rdp_msg.Rdp.rdp_response;

public class VirtualReaderHandler extends SimpleChannelInboundHandler<ByteBuf>{
	private VirtualReader vr;
	static Timer timer = new HashedWheelTimer(50L, TimeUnit.MILLISECONDS, 512);
	protected Logger log = Logger.getLogger("VirtualReaderHandler");
	
	public VirtualReaderHandler(VirtualReader vr) {
		super();
		this.vr = vr;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
		try {
			
			
			byte[] msgBytes = new byte[in.readableBytes()];
			in.readBytes(msgBytes);		
			vr.read(ctx,msgBytes);						

		} catch (NullPointerException e) {
			log.warning(e.getMessage());
		}		
	}
	
	
	  @Override
	    public void channelActive(ChannelHandlerContext ctx) throws Exception {
		 // sendAlive(ctx);
		  
		  
		  TimerTask task = new TimerTask() {
				public void run(Timeout timeout) throws Exception {
					sendAlive(ctx);
					// 任务执行完成后再把自己添加到任务solt上
					addTask(this);
				}
			};
			addTask(task);
	       
	    }

	  
		private void addTask(TimerTask task){
			timer.newTimeout(task, 10, TimeUnit.SECONDS);
			
		}
		
	
	private void sendAlive(ChannelHandlerContext ctx){
		System.out.println("in sendAlive");
		rdp_response.Builder ack = rdp_response.newBuilder();
		ack.setType(rdp_response.HeadType.keepAlive); 
		
		vr.write(ctx, ack.build().toByteArray());
		
	}

}
